package com.spring.security.app.jwt;

import com.spring.security.core.properties.SecurityConstants;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义token 生成器
 *
 * @author seabed_moon
 */
public class SpringJwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {

        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;

        token.setValue(getToken());

        token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken(getToken(), token.getExpiration()));

        Map<String, Object> additionalInformation = new HashMap<>(1, 0.75f);

        additionalInformation.put(SecurityConstants.CLIENT_ID, oAuth2Authentication.getOAuth2Request().getClientId());

        token.setAdditionalInformation(additionalInformation);

        return token;
    }

    /**
     * @Description 生成自定义token
     */
    private String getToken() {
        StringBuilder builder = new StringBuilder();
        return builder.append(RandomStringUtils.randomAlphanumeric(32)).append(".").append(RandomStringUtils.randomAlphanumeric(128)).toString();
    }

}
